//package com.ruoyi.websocket;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.web.socket.WebSocketHandler;
//import org.springframework.web.socket.config.annotation.EnableWebSocket;
//import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
//import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
//import org.springframework.web.socket.handler.TextWebSocketHandler;
//import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
//
//import java.util.List;
//import java.util.concurrent.Executors;
//import java.util.concurrent.ScheduledExecutorService;
//import java.util.concurrent.TimeUnit;
//
//@Configuration
//@EnableWebSocket
//@Slf4j
//public class WebSocketConfig implements WebSocketConfigurer {
//    // 创建一个共享线程池，以避免为每个连接创建新的线程池
//    private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
//    @Autowired
//    private MachineControlValueService machineControlValueService;
//    // 定义 WebSocket 消息处理器
//    @Override
//    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//        // 注册 WebSocket 端点
//        registry.addHandler(webSocketHandler(), "/ws/endpoint")
//                .addInterceptors(new HttpSessionHandshakeInterceptor()) // 可以添加握手拦截器
//                .setAllowedOrigins("*");  // 允许所有来源跨域访问
//    }
//
//    // 定义 WebSocket 消息处理器
//    @Bean
//    public WebSocketHandler webSocketHandler() {
//        return new TextWebSocketHandler() {
//            @Override
//            protected void handleTextMessage(org.springframework.web.socket.WebSocketSession session, org.springframework.web.socket.TextMessage message) throws Exception {
//                // 处理收到的消息
//                System.out.println("收到消息: " + message.getPayload());
//                // 如果收到 pong 消息，说明连接正常
//                if ("pong".equals(message.getPayload())) {
//                    System.out.println("收到客户端的 pong 响应");
//                }
////                synchronized (session) {  // 确保消息顺序发送
////                    System.out.println("收到消息: " + message.getPayload());
////                    // 处理消息并发送回复
////                    session.sendMessage(new org.springframework.web.socket.TextMessage("回复: " + message.getPayload()));
////                }
//                try {
//                    if (session.isOpen()) {
//                        session.sendMessage(new org.springframework.web.socket.TextMessage("ping"));
//                        System.out.println("发送 ping 消息到客户端");
//                    }
//                } catch (Exception e) {
//                    log.info("发送" + e.getMessage());
//                    System.err.println("发送 ping 消息失败：" + e.getMessage());
//                }
//
//            }
//
//            @Override
//            public void afterConnectionEstablished(org.springframework.web.socket.WebSocketSession session) throws Exception {
//                System.out.println("WebSocket 连接成功，Session ID: " + session.getId());
//                // 设置定时任务，每隔5秒发送一个 ping 消息
//                executorService.scheduleAtFixedRate(() -> {
//                    try {
//                        if (session.isOpen()) {
//                            log.info("发送 ping");
//                            //发送数据库信息将数据信息返给客户端
//                            ObjectMapper objectMapper = new ObjectMapper();
//                            List<MachineHomeListVo> byWebSocketList = machineControlValueService.getByWebSocketList();
//                            String json = objectMapper.writeValueAsString(byWebSocketList);
//                            session.sendMessage(new org.springframework.web.socket.TextMessage(json));
//                            System.out.println("发送 ping 消息到客户端");
//                            // 添加适当的延迟，确保任务执行时间接近10秒
//                            TimeUnit.SECONDS.sleep(1);
//                        }
//                    } catch (Exception e) {
//                        log.info("发送 ping 失败" + e.getMessage());
//                        System.err.println("发送 ping 消息失败：" + e.getMessage());
//                    }
//                }, 0, 5, TimeUnit.SECONDS);
////                Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
////                    try {
////                        if (session.isOpen()) {
////                            log.info("发送 ping");
////                            session.sendMessage(new org.springframework.web.socket.TextMessage("ping"));
////                            System.out.println("发送 ping 消息到客户端");
////                        }
////                    } catch (Exception e) {
////                        e.printStackTrace();
////                    }
////                }, 0, 5, TimeUnit.SECONDS);  // 每5秒发送一次
//            }
//
//            @Override
//            public void afterConnectionClosed(org.springframework.web.socket.WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
//                System.out.println("WebSocket 连接关闭，Session ID: " + session.getId());
//            }
//        };
//    }
//}
